package org.ajax.servlet;

import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.ajax.entity.User;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author CSY
 * @date 2024-11-19
 */
@WebServlet("/json.do")
public class JsonServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 操作比较麻烦 - 解决：Gson
//        String json = "{\"username\":\"zs\",\"age\":18}";
        User user = new User("张三",18);

        Gson gson = new Gson();

        String json = gson.toJson(user);

        PrintWriter out = resp.getWriter();
        out.println(json);
        out.flush();
        out.close();
    }
}
